package cn.zhaoyuening.service.impl;

import cn.zhaoyuening.lucenedemo2.domain.News;
import cn.zhaoyuening.service.IndexsService;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zhao on 2017/2/26.
 */
@Service
public class IndexsServiceImpl implements IndexsService {

    private IndexSearcher indexSearcher;

    @Autowired
    public void setIndexSearcher(IndexSearcher indexSearcher) {
        this.indexSearcher = indexSearcher;
    }

    public List<News> findByTitle(String title) throws IOException {
        List<News> newsList = new ArrayList<News>();
        Query query = new TermQuery(new Term("title",title));
        TopDocs topDocs = indexSearcher.search(query, 100);
        for(ScoreDoc scoreDoc:topDocs.scoreDocs){
            Document doc = indexSearcher.doc(scoreDoc.doc);
            String newsTitle = doc.get("title");
            String newsHref = doc.get("href");
            News news = new News();
            news.setTitle(newsTitle);
            news.setHref(newsHref);

            newsList.add(news);
        }
        return newsList;
    }
}
